<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{

    public $_id;
    const ERROR_LOCKED_ACCOUNT=10;

	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */


    public function authenticate() {
        $username = $this->username;
        $user = User::model()->find('username=?', array($username));
        if($user === NULL) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
            CUserLogs::MINOR("Invalid login.","empty");
        }

        // Case of wrong password
        else if(!$user->validatePassword($this->password, $this->username)) {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
            // if the password is wrong increment the lock_counter
            $user->lock_counter++;
            if($user->lock_counter>=Yii::app()->params["max_wrong_password"]) {
                CUserLogs::MAJOR("User entered a wrong password",$user);
                $user->locked = 1;
            }
            CUserLogs::MAJOR("User account has been locked because of too many wrong tries",$user);
            $user->save();

        }

        // Case of too many consecutive wrong passwords.
        else if($user->locked==1) {
            $this->errorCode=self::ERROR_LOCKED_ACCOUNT;
            CUserLogs::MINOR("Tried to log into his locked account",$user);
        }

        // All ok here. Reset the wrong password counter.
        else{
            $this->_id = $user->id;
            $this->username = $user->username;
            $this->errorCode=self::ERROR_NONE;
            $user->lock_counter = 0;

            $user->last_login = new CDbExpression('NOW()');
            $user->save();
            CUserLogs::INFO("User has logged in.",$user);
        }

        return $this->errorCode;
    }

}